import onmqtt
import ultrasound
import time

product_id = "497161"
device_id = "912249935"
auth_info = "ultrasound"


# 连接回调
def on_connect(client, userdata, flags, rc):
    print('Connected with result code ' + str(rc))

# 消息接收回调
def on_message(client, userdata, msg):
    print(msg.topic, msg.payload)
    topic = str(msg.topic).split('/')
    client.publish("$crsp/"+topic[1], payload='ok')

us = ultrasound.Ultrasound(trig=10, echo=9)
client = onmqtt.onenet_mqtt(pid=product_id, did=device_id, auth=auth_info)
client.on_connect = on_connect
client.on_message = on_message

# 获取和发布信息
while 1:
    distance = us.get_distance()
    print(distance)
    client.qpublish("distance", distance)
    time.sleep(1)

# client.loop_forever() # 响应